package zuo.biao.library.manager;

import ohos.agp.utils.TextTool;
import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.rdb.RawRdbPredicates;
import ohos.data.rdb.RdbOpenCallback;
import ohos.data.rdb.RdbStore;
import ohos.data.rdb.StoreConfig;
import ohos.data.resultset.ResultSet;
import zuo.biao.library.model.City;
import zuo.biao.library.util.StringUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 地区管理类
 *
 * @author Lemon
 * @use CityDB.getInstance(...).xxMethod(...)
 */
public class CityDB {
    private static final String CITY_DB_NAME = "city.db";
    private static final String CITY_TABLE_NAME = "city";
    private RdbStore db;

    private static  RdbOpenCallback callback =
            new RdbOpenCallback() {
                @Override
                public void onCreate(RdbStore store) {
                    store.executeSql(
                            "CREATE TABLE IF NOT EXISTS "
                                    + CITY_TABLE_NAME
                                    + " (id INTEGER PRIMARY KEY AUTOINCREMENT, province TEXT, city TEXT, latitude"
                                    + " DOUBLE, longitude DOUBLE)");
                }

                @Override
                public void onUpgrade(RdbStore store, int oldVersion, int newVersion) {}
            };

    public CityDB(Context context) {
        StoreConfig config = StoreConfig.newDefaultConfig(CITY_DB_NAME);
        DatabaseHelper helper = new DatabaseHelper(context);
        db = helper.getRdbStore(config, 1, callback, null);
    }

    private static CityDB cityDB;

    /**
     * 实例化
     * @param context c
     * @return CityDB
     */
    public static synchronized CityDB getInstance(Context context) {
        if (cityDB == null) {
            cityDB = openCityDB(context);
        }
        return cityDB;
    }

    private static CityDB openCityDB(Context context) {
        return new CityDB(context);
    }

    /**
     * 获取所有城市
     * @return list
     */
    public List<City> getAllCity() {
        List<City> list = new ArrayList<City>();
        RawRdbPredicates predicates = new RawRdbPredicates(CITY_TABLE_NAME);
        predicates.setWhereClause("SELECT * from " + CITY_TABLE_NAME);
        String[] columns = new String[] {"id", "province", "city", "latitude", "longitude"};
        ResultSet resultSet = db.query(predicates, columns);

        while (resultSet.goToNextRow()) {
            String province = resultSet.getString(1);
            String city = resultSet.getString(2);
            Double latitude = resultSet.getDouble(3);
            Double longitude = resultSet.getDouble(4);
            City item = new City(province, city, latitude, longitude);
            list.add(item);
        }
        return list;
    }

    /**
     * 获取所有省
     * @return r
     */
    public List<String> getAllProvince() {
        List<String> list = new ArrayList<String>();
        String[] columns = new String[] {"id", "province", "city", "latitude", "longitude"};
        RawRdbPredicates predicates = new RawRdbPredicates(CITY_TABLE_NAME);
        predicates.setWhereClause("SELECT distinct province from " + CITY_TABLE_NAME);
        ResultSet resultSet = db.query(predicates, columns);
        while (resultSet.goToNextRow()) {
            String province = resultSet.getString(1);
            list.add(province);
        }
        return list;
    }

    /**
     * 拿到省的所有 地级市
     * @param province province
     * @return List<String>
     */
    public List<String> getProvinceAllCity(String province) {
        province = StringUtil.getTrimedString(province);
        if (province.length() <= 0) {
            return null;
        }

        List<String> list = new ArrayList<String>();
        String[] columns = new String[] {"id", "province", "city", "latitude", "longitude"};
        RawRdbPredicates predicates = new RawRdbPredicates(CITY_TABLE_NAME);
        predicates.setWhereClause("SELECT distinct city from " + CITY_TABLE_NAME + " where province =  " + province);
        ResultSet resultSet = db.query(predicates, columns);
        while (resultSet.goToNextRow()) {
            String city = resultSet.getString(2);
            list.add(city);
        }
        return list;
    }

    /**
     * 拿到所有的 县或区
     *
     * @return
     */
    public List<String> getAllCountry(String province, String city) {
        province = StringUtil.getTrimedString(province);
        if (province.length() <= 0) {
            return null;
        }

        List<String> list = new ArrayList<String>();
        String[] columns = new String[] {"id", "province", "city", "latitude", "longitude"};
        RawRdbPredicates predicates = new RawRdbPredicates(CITY_TABLE_NAME);
        predicates.setWhereClause("SELECT distinct city from " + CITY_TABLE_NAME + " where province =  " + province);
        ResultSet resultSet = db.query(predicates, columns);
        while (resultSet.goToNextRow()) {
            String city1 = resultSet.getString(2);
            list.add(city1);
        }
        return list;
    }


    /**
     * 获取城市
     * @param city c
     * @return r
     */
    public City getCity(String city) {
        if (TextTool.isNullOrEmpty(city)) {
            return null;
        }
        City item = getCityInfo(parseName(city));
        if (item == null) {
            item = getCityInfo(city);
        }
        return item;
    }

    /**
     * 去掉市或县搜索
     *
     * @param city city
     * @return String
     */
    private String parseName(String city) {
        if (city.contains("市")) { // 如果为空就去掉市字再试试
            String[] subStr = city.split("市");
            city = subStr[0];
        } else if (city.contains("县")) { // 或者去掉县字再试试
            String[] subStr = city.split("县");
            city = subStr[0];
        }
        return city;
    }

    private City getCityInfo(String city) {
        String[] columns = new String[] {"id", "province", "city", "latitude", "longitude"};
        RawRdbPredicates predicates = new RawRdbPredicates(CITY_TABLE_NAME);
        predicates.setWhereClause("SELECT * from " + CITY_TABLE_NAME + " where city=" + city);
        ResultSet resultSet = db.query(predicates, columns);

        if (resultSet.goToNextRow()) {
            String province = resultSet.getString(1);
            String cityN = resultSet.getString(2);
            Double latitude = resultSet.getDouble(3);
            Double longitude = resultSet.getDouble(4);

            City item = new City(province, cityN, latitude, longitude);
            return item;
        }
        return null;
    }

    /**
     * 查询附近的城市
     * 画正方形
     * @param sCity sCity
     * @return list
     */
    public List<String> getNearbyCityList(String sCity) {
        City city = getCity(sCity);
        List<String> nearbyCitysList = new ArrayList<String>();
        // 根据常跑地信息画正方形地域
        double lat = city.getLatitude() + 0.9;
        double lon = city.getLongitude() + 0.9;
        double lat1 = city.getLatitude() - 0.9;
        double lon1 = city.getLongitude() - 0.9;

        String[] columns = new String[] {"id", "province", "city", "latitude", "longitude"};
        RawRdbPredicates predicates = new RawRdbPredicates(CITY_TABLE_NAME);
        predicates.setWhereClause(
                "SELECT * from "
                        + CITY_TABLE_NAME
                        + " WHERE LATITUDE < "
                        + lat
                        + " AND LATITUDE > "
                        + lat1
                        + " AND LONGITUDE <"
                        + lon
                        + " AND LONGITUDE > "
                        + lon1);
        ResultSet resultSet = db.query(predicates, columns);

        while (resultSet.goToNextRow()) {
            String nearbyCity = resultSet.getString(2);
            nearbyCitysList.add(nearbyCity);
        }
        return nearbyCitysList;
    }
}
